package com.crm.web.page;

import org.apache.tapestry.html.BasePage;
import org.apache.tapestry.annotations.InjectState;
import org.apache.tapestry.annotations.InjectPage;
import org.apache.tapestry.IPage;
import org.apache.tapestry.event.PageEvent;
import org.apache.tapestry.event.PageBeginRenderListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.javaforge.tapestry.spring.annotations.InjectSpring;
import com.crm.service.ICustomerService;
import com.crm.service.IContactService;
import com.crm.model.User;
import com.crm.model.Customer;

import java.util.List;
import java.util.ArrayList;

/**
 * @author <a href="mailto:huang0510@hotmail.com">HuangHuang</a>
 * @version $Id$
 */
public abstract class ContactOfCustomer extends BasePage implements PageBeginRenderListener {

    private static Log log = LogFactory.getLog(ContactOfCustomer.class);
    private int count;

    @InjectSpring("customerService")
    public abstract ICustomerService getCustomerServ();

    @InjectSpring("contactService")
    public abstract IContactService getContactService();

    @InjectState("userSession")
    public abstract User getUserSession();

    @InjectPage("ContactList")
    public abstract ContactList getContactListPage();

    public void pageBeginRender(PageEvent event){
        if(getUserSession().getId()==null)
            event.getRequestCycle().sendRedirect("app?page=SysPageError&service=page");
    }

    public String getRecordCount() {
        return "共" + count + "条记录";
    }

    public List getEntries(){
        try{
            List list = getCustomerServ().getCustomers(getUserSession());
            count = list.size();
            return list;
        }
        catch(Exception e){
            log.warn(getUserSession().getUsername()
                    + ": The error happened when customer information loading for page ContactOfCustomer! Cause by:"
                    + e.getMessage());
            e.printStackTrace();
            return new ArrayList();
        }
    }

    public IPage onShowDetails(Customer customer) {
        ContactList page = getContactListPage();
        page.setCustomer(customer);
        return page;
    }
}
